package xyz.heyaoshare.config.mybatis.listener;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.annotation.InsertListener;
import xyz.heyaoshare.config.mybatis.entity.BaseEntity;
import xyz.heyaoshare.config.mybatis.entity.SimpleEntity;
import xyz.heyaoshare.utils.StrUtils;

import java.time.LocalDateTime;

/**
 * 新增前置处理器
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午11:02
 */
public class InsertListenerHandler implements InsertListener {

    @Override
    public void onInsert(Object entity) {
        if (entity instanceof BaseEntity baseEntity) {
            String loginId = getLoginId();
            LocalDateTime currentTime = LocalDateTime.now();
            if (StrUtils.isNotBlank(loginId)) {
                baseEntity.setCreator(loginId);
                baseEntity.setUpdater(loginId);
            }
            baseEntity.setCreateTime(currentTime);
            baseEntity.setUpdateTime(currentTime);
        }
        if (entity instanceof SimpleEntity simpleEntity) {
            simpleEntity.setDeleted(Boolean.FALSE);
            simpleEntity.setVersion(0L);
        }
    }

    private String getLoginId() {
        try {
            return StpUtil.getLoginIdAsString();
        } catch (Exception e) {
            return "";
        }
    }

}
